package com.tanhua.server.service;

import com.tanhua.autoconfig.template.AipTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.domain.UserInfo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.vo.ErrorResult;
import com.tanhua.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoService {
    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipTemplate aipTemplate;

    /**
     * 保存用户信息
     * @param userInfo
     */
    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    /**
     * 更新用户头像
     * @param headPhoto
     * @param id
     * @throws IOException
     */
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //将图片上传到阿里云oss
        String url = ossTemplate.saveMassage(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

        //用百度云人脸识别判断图片是否合法
        boolean recognition = aipTemplate.recognition(url);

        if(!recognition){
            //图片不合法，抛出错误
            throw new BusinessException(ErrorResult.faceError());
        }else{
            //图片合法，更新数据库数据
            UserInfo userInfo = new UserInfo();
            userInfo.setId(Long.valueOf(id));
            userInfo.setAvatar(url);
            userInfoApi.update(userInfo);
        }
    }

    /**
     * 根据id查询用户
     * @param userId
     */
    public UserInfoVo findById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        UserInfoVo vo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo,vo); //copy同名同类型的属性
        //userInfo中age为integer，userInfoVo中age为string，与前端对应
        if(userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }

    /**
     * 保存用户数据
     * @param userInfo
     */
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }
}
